package sql

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

type User struct {
	gorm.Model
	Name  string `gorm:"column:name;type:varchar(25)"`
	Phone string `gorm:"column:phone;type:varchar(11);uniqueindex"`
	Age   int    `gorm:"column:age;"`
}

type Dog struct {
	gorm.Model
	Name   string `gorm:"column:name;type:varchar(25)"`
	Age    int    `gorm:"column:age;"`
	UserId int    `gorm:"column:user_id;not null"`
}

type Pig struct {
	gorm.Model
	Name string `gorm:"column:name;type:varchar(25)"`
}

var DB *gorm.DB

func init() {
	dsn := "root:12345678@tcp(127.0.0.1:3306)/study_gorm?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("数据库连接失败")
	}
	if err := db.AutoMigrate(&User{}, &Dog{}); err != nil {
		panic("初始化数据库失败")
	}
	DB = db
	//:设置数据库的连接池参数
	sqlDB, err := DB.DB()
	sqlDB.SetConnMaxLifetime(time.Hour) //:连接时长1h
	sqlDB.SetMaxIdleConns(5)            //:连接池最大的空闲数
	sqlDB.SetMaxOpenConns(5)            //:连接池最大的连接数

}
